<template>
  <div class="toChatService">
    <!-- <x-header title="车网通客服娜娜" :left-options="{backText:''}" class="whiteHeader"></x-header> -->
    <header class="whiteHeader">
      <div class="kefuBack" @click="backOneHistory"></div>
      <span>车网通客服{{ targetUserId }}</span>
    </header>
    <div class="container" :class="{containershow:toShowMoreBol}">
    <!-- {{ msgArr }} -->
      <div class="chat-container" v-for="(item,index) in msgArr" :key="index">
      <!-- <div class="widget-date">
        <span>1月2日 下午15:09</span>
      </div> -->
      <!-- 自己的消息 -->
      <div class="widget-right" v-if="item.to==targetUserId">
        <img src="./../../assets/image/customer/fdas.png" alt="" class="avatar userImg">
        <div class="widget-msg-wrapper">
          <div class="icon-corner-left"></div>
          <div class="widget-msg-container">
            <pre v-if="item.type === 'txt'">{{item.msg}}</pre>
            <!-- {{item}} -->
            <img :src="item.url" alt="" v-if="item.type === 'img'" class="infoImg" @click="showBigPic(item.url)">
            <!-- test 测试发图 -->
            <!-- <img :src="item.file.url" alt="" v-if="item.type === 'img'" class="infoImg" @click="showBigPic(item.file.url)"> -->
          </div>
          <p v-if="item.ReceivedMessage&&!item.ReadMessage">送达</p>
          <p v-if="item.ReceivedMessage&&item.ReadMessage">已读</p>
        </div>
      </div>
      <!-- 我方客服消息 -->
      <div class="widget-left" v-if="item.to==userId">
        <img src="./../../assets/image/customer/fdas.png" alt="" class="avatar userImg">
        <div class="widget-msg-wrapper">
          <div class="icon-corner-right"></div>
          <div class="widget-msg-container">
            <!-- {{item}} -->
            <img v-if="item.type === 'img'" :src="item.url" alt="" class="infoImg" @click="showBigPic(item.url)">
            <pre v-if="item.type === 'txt'">{{item.message.data}}</pre>
            <!-- <img src="" alt="" class="infoImg"> -->
          </div>
        </div>
      </div>
    </div>
    </div>
    <div class="widget-send-wrapper"></div>

<!--     <footer class="footerBody" :class="{widgetSendWrappershow:toShowMoreBol}">
      <span class="footerVoice" @click="toShowVoice">
        <img src="./../../assets/image/customer/yuying.png" alt="" v-if="!VoiceBtnBol">
        <img src="./../../assets/image/customer/jianpan.png" alt="" v-if="VoiceBtnBol">
      </span>
      <div class="chat-send">
        <textarea autocomplete="off" v-model="textMsg" v-if="!VoiceBtnBol" rows="1"></textarea>
        <span class="MsgExpression" @click="toShowExpression"><img src="./../../assets/image/customer/biaoqing.png" alt="" v-if="!VoiceBtnBol"></span>
        <button class="toSendVoice" @click="toSendVoice" v-if="VoiceBtnBol">按住说话</button>         
        <button class="toSend" @click="toSendMsg" v-if="VoiceBtnBol">发送</button> 
      </div>
      <span class="footerAdd"  v-if="!ismsgBol" @click="toShowMore">
        <img src="./../../assets/image/customer/jiahao.png" alt="">
      </span>
      <button class="toSend" @click="toSendMsg" v-if="ismsgBol">发送</button>
    </footer> 
 -->
    <footer class="footerBody" :class="{widgetSendWrappershow:toShowMoreBol}">
      <div class="chat-send">
        <textarea autocomplete="off" v-model="textMsg" v-if="!VoiceBtnBol" rows="1" @focus="toShowMoreBol = false"></textarea><!-- @keyup.enter="toSendMsg" -->
        <!-- <input type="text" v-model="textMsg" v-if="!VoiceBtnBol" @keyup.enter="toSendMsg" @focus="toShowMoreBol = false"> -->
        <div class="toSend" @click="toSendMsg"> 发送</div>
      </div>
      <span class="footerAdd" @click="toShowMore">
        <img src="./../../assets/image/customer/jiahao.png" alt="">
      </span>
    </footer>
    <div class="toShowMore" v-if="toShowMoreBol">
      <!-- <input type="file" multiple="multiple" accept="image/*" capture="camera" class="morecamera"> -->
      <!-- <input type="file" multiple="multiple" accept="image/*" class="morecamera" id="image" @click="sendPrivateText"> -->
      <div class="imgPickBox">
        <input type="file" multiple="multiple" accept="image/*" id="image" @change="sendPrivateImg">
      </div>
    </div>
    <!-- 看大图 -->
    <div class="seeBigPicMask" v-if="showBigImg">
      <img :src="bigImgUrl" alt="" @click="closeBigPic">
    </div>
  </div>
</template>
<script>
import {XHeader} from "vux";
import { getCookie } from "../../util/commonUtils";

export default {
  name:'toChatService',
  data () {
    return{
      targetUserId: '', // 发给对象消息ID
      msgArr: '', // 本地存聊天的记录
      userId: '',  // 用户的id
      msgBol: false, // 消息的发送按钮
      VoiceBtnBol: false, // 显示Voice按钮
      toShowMoreBol: false, // 显示更多
      textMsg: '',// 发送的消息
      showBigImg: false, // 是否展示大图
      bigImgUrl: '' // 大图的url
    }
  },
  // 创建（实例创建完成）
  created(){
    // 登录环信
    this.WEBIM_login()
  },
  // 计算属性  
  beforeDestroy(){
    this.$imConn.close()
  },
  computed: {
    ismsgBol(){
      if(this.textMsg!=""){
        return this.msgBol =true;
      }else{
        this.msgBol = false;
      }
    }
  },
  methods: {
    WEBIM_login(){
      // 获取登录的手机号
      let that = this
      if(getCookie('loginkey')){
        this.userId = getCookie('loginkey')
        console.log(this.userId)
        this.userphone = getCookie('TEL')
      }else{
        this.$vux.confirm.show({
          title:'提示',
          content:'请先登录',
          onConfirm () {
            that.$router.push('/login');
          }
        })
      }
      let WebIM = this.$WebIM
      let imConn = this.$imConn
      // 传手机号后台会帮我们注册
      this.$fetchPost('/HelpMessageType/helloToClientService', {
        USER_ID: this.userId,
        PHONE: this.userphone
      }).then(res=>{
        // 登录
        if(!localStorage.getItem('TARGET_USER_ID')){
          localStorage.setItem('TARGET_USER_ID' , res.TARGET_USER_ID)
          localStorage.setItem('USER_ID', this.userId)
        }
        let options = { 
          apiUrl: WebIM.config.apiURL,
          user: that.userId,
          pwd: '123456',
          appKey: WebIM.config.appkey,
          success: function (token) {
            console.log('l_sucess') // 登陆成功
            // 存对话相关信息
            that.targetUserId = localStorage.getItem('TARGET_USER_ID')
            // that.userId = localStorage.getItem('USER_ID')
            if(localStorage.getItem('msgArr')){
              that.msgArr = JSON.parse(localStorage.getItem('msgArr'))
            }else{
              that.msgArr = []
            }
            // 历史记录
            that.listenMsg()
          },
        };
        imConn.open(options); // 登录
      })
    },
    // 看大图
    showBigPic (url) {
      // console.log(url)
      this.bigImgUrl = url
      this.showBigImg = true
    },
    // 关闭大图
    closeBigPic () {
      this.showBigImg = false
      this.bigImgUrl = ''
    },
    // 每次发送完消息，将视口移动至最下方
    moveViewToBelow () {
      window.scrollTo(0, document.querySelector('.container').clientHeight)
    },
    toSendMsg(){
      let that = this
      if(!!!getCookie('loginkey')){
        this.$vux.confirm.show({
          title:'提示',
          content:'请先登录',
          onConfirm () {
            that.$router.push('/login');
          }
        })
        return
      }
      if(this.textMsg!=''){
        this.sendPrivateText(this.textMsg)
        this.textMsg = ''
      }
    },
    sendPrivateText(msgtext) {
      let that = this
      let imConn = this.$imConn
      var id = imConn.getUniqueId();                 // 生成本地消息id
      var msg = new WebIM.message('txt', id);      // 创建文本消息
      msg.set({
          msg: msgtext,
          from: this.userId,         // 消息内容
          to: this.targetUserId,         // 接收消息对象（用户id）
          roomType: false,
          success: function (id, serverMsgId) {
              console.log('Send private text success')
              that.moveViewToBelow()
          },
          fail: function(e){
              console.log("Send private text error");
          }
      });
      msg.body.chatType = 'singleChat';
      imConn.send(msg.body);
      this.msgArr.push(msg.body)
      localStorage.setItem('msgArr', JSON.stringify(this.msgArr))
    },
      // 单聊发送图片消息
    sendPrivateImg() {
      let that = this
      if(!!!getCookie('loginkey')){
        this.$vux.confirm.show({
          title:'提示',
          content:'请先登录',
          onConfirm () {
            that.$router.push('/login');
          }
        })
        return
      }
      let imConn = this.$imConn
      var id = imConn.getUniqueId();                   // 生成本地消息id
      var msg = new WebIM.message('img', id);        // 创建图片消息
      var input = document.getElementById('image');  // 选择图片的input
      var file = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
      var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true
      };
      if (file.filetype.toLowerCase() in allowType) {
        let id = null
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: this.targetUserId,                       // 接收消息对象
            roomType: false,
            chatType: 'singleChat',
            onFileUploadError: function (err) {      // 消息上传失败
                console.log('消息上传失败' + err);
            },
            onFileUploadComplete: function (data) {   // 消息上传成功
                // console.log('onFileUploadComplete');
                let url = data.uri + "/" + data.entities[0].uuid // 图片地址
                console.log('我发送的图片完成' + url)
                console.log(JSON.stringify(data))
                let imgMsg = {
                  id: id,
                  type: 'img',
                  url: url,
                  to: that.targetUserId // 标记该图片消息为'自己发送给客服'
                }
                that.msgArr.push(imgMsg)
                localStorage.setItem('msgArr', JSON.stringify(that.msgArr))
                that.toShowMore()
                that.moveViewToBelow()
            },
            success: function (data) {                // 消息发送成功
                console.log('Success');
            },
            flashUpload: WebIM.flashUpload
          };
          msg.set(option);
          imConn.send(msg.body);
          id = msg.body.id // 该消息id
      }
    },
    // 监听发生消息改变 实时更新
    listenMsg(){
      let that = this
      this.$imConn.listen({
        onOpened:function(message){
          // 监听连接成功
        },
        // 接受到文本消息
        onTextMessage:function(message){
          console.log('收到的文本消息 ' + JSON.stringify(message))
          let data = {
            type: 'txt',
            message: message,
            to: that.userId
          }
          that.msgArr.push(data)
          localStorage.setItem('msgArr', JSON.stringify(that.msgArr))
        },
        onClosed: function ( message ) {
        },
        onOnline: function () {
          console.log('本机网络连接成功')
        },                  //本机网络连接成功
        onOffline: function () {
          console.log('本机网络掉线')
        },
        // 收到图片消息
        onPictureMessage: function (message) {
          console.log("Location of Picture is ", message.url);
          let data = {
            type: 'img',
            url: message.url,
            to: that.userId
          }
          console.log(data)
          that.msgArr.push(data)
        }, //收到图片消息
        onDeliveredMessage: function(message){
          console.log('onDeliveredMessage')
          console.log(message)
        },
        // 失败
        onError: function ( message ) {
          console.log(message)
        },
        // 对方收到消息
        onReceivedMessage: function(message){
          console.log('message' + JSON.stringify(message))
          for(let i =0; i<that.msgArr.length; i++){
            if(that.msgArr[i].id==message.id){
              // 此消息已成功发送给对方
              // that.msgArr[i].mid = message.mid;
              that.$set( that.msgArr[i],'mid',message.mid)
              // that.msgArr[i].ReceivedMessage = true
              that.$set( that.msgArr[i],'ReceivedMessage',true)
              // console.log(that.msgArr)
            }
          }
        },
        // 对方已读消息
        onReadMessage: function(message){
          for(let i =0; i<that.msgArr.length; i++){
            if(that.msgArr[i].mid==message.mid){
              // 此消息已成功发送给对方
              that.$set( that.msgArr[i],'ReadMessage',true)
              // that.msgArr[i].ReadMessage= true;
              // console.log(that.msgArr)
            }
          }
        },        //收到消息已读回执
      })
    },
    // 显示语言消息
    toShowVoice(){
      this.VoiceBtnBol = !this.VoiceBtnBol;
    },
    // 按住说话
    toSendVoice(){},
    // 表情
    toShowExpression(){},
    // 发送更多
    toShowMore(){
      this.toShowMoreBol = !this.toShowMoreBol;
    },
    // 后退
    backOneHistory () {
      window.history.go(-1)
    }
  },
  components:{
    XHeader
  }
   } 
</script>
<style lang="less" scoped>
.whiteHeader{
  position: fixed;
  width: 100%;
  height: .8rem;
  line-height: .8rem;
  background-color:#ff4848;
  color: #fff;
  text-align: center;
  .kefuBack{
    position: absolute;
    width: .4rem;
    height: .4rem;
    left: .4rem;
    top: .3rem;
    &:before{
      content: "";
      border: 1px solid #fff!important;
      border-width: 1px 0 0 1px!important;
      font-weight: bold;
      position: absolute;
      width: 12px;
      height: 12px;
      border: 1px solid #ccc;
      border-width: 1px 0 0 1px;
      -webkit-transform: rotate(315deg);
      transform: rotate(315deg);
      top: 0;
      left: 0;
    }
  }
}
.toChatService{
  min-height: 100%;
  height: 100%;
  font-size: 0.3rem;
  .container{
    padding-top: 1.8rem;
    background-color: #efeff4;
    padding-bottom: 1rem;
    position: relative;
    bottom: 1rem;
    .chat-container{
    padding-top: 0rem;
    overflow: hidden;
    .widget-date{
      span{
        border-radius: 0.1rem;
        padding: 0 0.2rem;
        background-color: #DCDEDD;
        color:#BEC0BF;
      }
    }
    .widget-right{
      float: right;
      display: block;
      font-size: 0.34rem;
      text-decoration: none;
      overflow: hidden;
      width: 98%;
      text-align: left;
      margin: 0.2rem 0;
      margin-bottom: -0.7rem;
      img.userImg{
        max-width: 2.72rem;
        height: 0.72rem;
        margin-right: 0.1rem;
        float: right;
      }
      img.infoImg{
        max-width: 2.72rem;
        float: right;
      }
      .widget-msg-wrapper{
        clear: both;
        right: 1rem;
        top: -0.75rem;
        background: #D1E1E1;
        border: 1px solid #e5e5e5;
        position: relative;
        float: right;
        display: inline-block;
        border-radius: 0.15rem;
        max-width: 4rem;
        padding: 0.1rem 0rem;
        .icon-corner-left{
          float: left;
          width: auto;
          max-width: calc(85% - 50px);
          border-color: #e5e5e5;
          background-color: #fff;
          margin-left: 0.45rem;
        }
        .icon-corner-left:before{
          transform: rotate(45deg);
          background-color: #D1E1E1;
          right: -0.1rem;
          content: "";
          position: absolute;
          width: 0.15rem;
          height: 0.15rem;
          top: 0.33rem;
        }
        .widget-msg-container{
          display: inline-block;
          border-radius: 0.06rem;
          max-width: 4rem;
          padding: 0.1rem;
          min-width: 0.2rem;
          min-height: 0.2rem;
          vertical-align: middle;
          text-align: left;
          color: #000;
          pre{
            word-break: break-word;
            white-space: pre-wrap;
          }
        }
        p{
          position: absolute;
          left: -0.7rem;
          top: 0.2rem;
          font-size: 0.24rem;
        }
      }
    }
    .widget-left{
      float: left;
      display: block;
      text-decoration: none;
      font-size: 0.34rem;
      overflow: hidden;
      width: 98%;
      text-align: left;
      margin: 0.2rem 0;
      margin-bottom: -0.7rem;
      img.userImg{
        max-width: 2.72rem;
        height: 0.72rem;
        margin-left: 0.1rem;
        float: left;
      }
      img.infoImg{
        max-width: 2.72rem;
        float: left;
      }
      .widget-msg-wrapper{
        clear: both;
        left: 1rem;
        top: -0.75rem;
        background:#fff;
        border: 1px solid #e5e5e5;
        position: relative;
        float: left;
        display: inline-block;
        border-radius: 0.15rem;
        max-width: 4rem;
        padding: 0.1rem 0rem;
        .icon-corner-right{
          float: left;
          width: auto;
          max-width: calc(85% - 50px);
          border-color: #e5e5e5;
          background-color: #fff;
          // margin-right: 0.45rem;
        }
        .icon-corner-right:before{
          transform: rotate(45deg);
          background-color: #fff;
          left: -0.08rem;
          content: "";
          position: absolute;
          width: 0.15rem;
          height: 0.15rem;
          top: 0.33rem;
        }
        .widget-msg-container{
          display: inline-block;
          border-radius: 0.06rem;
          max-width: 4rem;
          padding: 0.1rem 0.1rem 0.1rem .45rem;
          min-width: 0.2rem;
          min-height: 0.2rem;
          vertical-align: middle;
          text-align: left;
          color: #000;
          pre{
            word-break: break-word;
            white-space: pre-wrap;
          }
        }
      }
    }
  }
  }
}
.footerBody{
  position: fixed;
  bottom: 0;
  border-top: 1px solid #ccc;
  height: 0.8rem;
  width: 100%;
  display: flex;
  background-color: #fff;
  .footerVoice{
    padding: 0.1rem;
    img{
      width: 0.6rem;
      height: 0.6rem;
    }
  }
  .footerAdd{
    padding: 0.1rem;
    img{
      width: 0.6rem;
      height: 0.6rem;
    }
  }
  .chat-send{
    position: relative;
    flex: 1;
    display: flex;
    padding: 0 0.1rem;
    textarea{
      resize: none;
      height: 0.6rem;
      font-size: 0.3rem;
      flex: 1;
      // text-align: center;
      margin-top:0.1rem;
      border: none; 
      border-bottom: 1px solid #ccc;
      padding: 0.1rem 0.6rem 0.1rem 0.2rem;
      // background:url('./../../assets/image/customer/biaoqing.png') no-repeat;
      // background-size: 0.5rem 0.5rem;
      // background-position: 5rem 0;
    }
    .MsgExpression{
      position: absolute;
      right: 0rem;
      top: 0.1rem;
      img{
        width: 0.5rem;
        height:0.5rem;
      }
    }
    .toSendVoice{
      flex: 1;
      border-radius: 3px;
      background-color: #fff;
      border: 1px solid #333;
      height: 0.6rem;
      padding: 0.1rem 0.2rem;
      margin-top: 0.1rem;
      margin-left: 0.1rem;
    }
  }
  .toSend{
    width: 1.5rem;
    height: 0.65rem;
    background: #ff4848;
    line-height: .65rem;
    margin-top: 0.05rem;
    border-radius: 3px;
    color: #fff;
  }
}
.widgetSendWrappershow{
  position: fixed;
  bottom: 2rem;
}
.containershow{
  padding-bottom: 3rem!important;
  overflow-y:auto;
  position: relative;
  bottom: 3rem;
}
.toShowMore{
  position: fixed;
  width: 100%;
  display: flex;
  bottom: 0rem;
  height: 2rem;
  border-top:1px solid #999; 
  background-color: #fff;
  margin-bottom: 0;
  .tosendTU{
    width: 1rem;
    height: 1rem;
    background-color:#fff; 
  }
  .imgPickBox{
    width: 1rem;
    height: 1rem;
    position: relative;
    background: url() #efefef;
    background-size: 100%;
    margin: 0.4rem;
    input{
      position:absolute;
      top: 0;
      left: 0;
      width: 1rem;
      height: 1rem;
      opacity: 0;
    }
  }

}
.morecamera{
  margin: 0.4rem;
}
// 查看大图
.seeBigPicMask{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .5);
  z-index: 401;
  img{
    width: 100%;
    position: absolute;
    z-index: 402;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
  }
}



</style>
